/*
 * @Description: 权限规则 - 权限列表 - 操作组件
 * @Author: Rfan
 * @Date: 2022-04-08 09:07:14
 * @LastEditTime: 2022-05-25 09:01:57
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Input, Space, Typography } from 'antd';
import classNames from 'classnames/bind';
import ExpGeneratorDialog, { TScopeType } from '@/components/ExpGeneratorDialog';
import { jsonClone } from '@/utils';
import { useUseRuleContext } from '../../contexts/UseRuleContext';

import styles from '../../styles/list.module.scss';

const cx = classNames.bind(styles);

const RuleOperate = () => {
  const {
    selectFond,
    selectAT,
    selectLevel,
    ruleSelectItems,
    addRightSpecFunc,
    deleteRightSpecFunc
  } = useUseRuleContext();
  // 添加规则弹窗状态
  const [addRuleVisible, setAddRuleVisible] = useState(false);
  // 传入ExpGeneratorDialog的范围参数
  const [scope, setScope] = useState<TScopeType>({
    atCode: 0,
    atType: 0,
    fondsId: 0,
    archiveTypeId: 0,
    level: []
  });

  useEffect(() => {
    if (selectLevel.level) {
      setScope({
        fondsId: selectFond.id,
        archiveTypeId: selectAT.id,
        atCode: selectAT.atCode,
        atType: selectAT.atType,
        level: [selectLevel.level]
      });
    }
  }, [selectLevel]);

  /**
   * @description: 关闭添加规则弹窗，根据参数判断取消还是保存
   * @param {string} condition 添加的规则，保存时使用
   * @param {TScopeType} scope 传入的环境，用于同意参数，保存时使用
   */
  const closeExpDialog = (condition?: string, scope?: TScopeType) => {
    if (condition) {
      console.log({ condition });
      const params = jsonClone(scope);
      params.level = scope.level[0];
      params.ruleDescription = condition;
      addRightSpecFunc(params).then(() => {
        setAddRuleVisible(false);
      });
    } else {
      setAddRuleVisible(false);
    }
  };

  /**
   * @description: 删除规则
   */
  const delRule = () => {
    deleteRightSpecFunc(ruleSelectItems);
  };

  return (
    <div className="filter-container">
      <p className={cx('page-title')}>
        {selectAT.atName}：规则列表{' '}
        <Typography.Text type="secondary">
          {' '}
          点击规则可查看规则被授予了哪些用户或组织
        </Typography.Text>
      </p>
      <Space size="small">
        <Input.Search />
        <Button type="primary" disabled>
          筛选
        </Button>
        <Button
          disabled={ruleSelectItems.length <= 0}
          onClick={() => {
            delRule();
          }}
        >
          删除规则
        </Button>
        <Button
          disabled={!selectLevel.level}
          onClick={() => {
            setAddRuleVisible(true);
          }}
        >
          添加规则
        </Button>
      </Space>
      {useMemo(
        () => (
          <ExpGeneratorDialog visible={addRuleVisible} scope={scope} onClose={closeExpDialog} />
        ),
        [addRuleVisible, selectLevel]
      )}
    </div>
  );
};

export default RuleOperate;
